package com.sc.nft.helper;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.huifu.saturn.cfca.CFCASignature;
import com.huifu.saturn.cfca.SignResult;
import com.huifu.saturn.cfca.VerifyResult;
import com.sc.nft.config.hf.HfConfig;
import com.sc.nft.config.sand.SandConfig;
import com.sc.nft.dao.BankDetailsDao;
import com.sc.nft.dao.HfFastBankDao;
import com.sc.nft.dao.UserHfExtDao;
import com.sc.nft.entity.*;
import com.sc.nft.entity.vo.HfFastBankVO;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.util.BankCardUtil;
import com.sc.nft.util.OrderNoUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.Map;

@Component
@RequiredArgsConstructor
@Slf4j
public class SmartSupplyHelper {


    @Value("${supply.smart.appKey}")
    private String appKey;
    @Value("${supply.smart.secretId}")
    private String secretId;
    @Value("${supply.smart.requestUrl}")
    private String requestUrl;
    @Value("${supply.smart.sendNotifyUrl}")
    private String sendNotifyUrl;


    private final String CREATE_ORDER="/apiOrder/addOrderObjectMall";
    private final String CONFIRM_ORDER="/api/apiPublicNotify";
    private final String AFTER_SALES="/apiAfterSales/saveApply";


    public JSONObject createOrder(MallProduct product,MallProductSpecs productSpecs,MallOrder order){
        JSONObject params = new JSONObject();
        params.put("address",order.getUserAddress());
        params.put("area",order.getArea());
        params.put("billHeader",StrUtil.EMPTY);
        params.put("billType",0);
        params.put("isBill",0);
        params.put("city",order.getCity());
        params.put("linkMan",order.getUserRealName());
        params.put("mobile",order.getUserTel());
        params.put("payType",99);
        params.put("province",order.getProvince());
        params.put("taxNumber",StrUtil.EMPTY);
        JSONArray orderDetailArray = new JSONArray();
        JSONObject orderDetail = new JSONObject();
        orderDetail.put("appOrderSn",order.getOrderNo());
        orderDetail.put("channel",1);
        orderDetail.put("deliveryWay",3);
        orderDetail.put("goodId",product.getProductCode());
        orderDetail.put("goodName",product.getProductName());
        orderDetail.put("inventoryId",productSpecs.getInventoryId());
        orderDetail.put("navigateImg1",StrUtil.EMPTY);
        orderDetail.put("productId",productSpecs.getSpecsCode());
        orderDetail.put("quantity",order.getTotalNum());
        orderDetail.put("salePrice",0);
        orderDetail.put("storeId",0);
        orderDetail.put("brandId",0);
        orderDetail.put("productPrice",0);
        orderDetailArray.add(orderDetail);
        params.put("orderDetailList",orderDetailArray);
       return sendRequest(params,CREATE_ORDER);
    }


    /**
     * 售后
     * @return
     */
    public JSONObject afterSales(MallOrder mallOrder,Integer count){
        JSONObject params = new JSONObject();
        params.put("isRefund",mallOrder.getRefundType());
        params.put("orderDetailId",mallOrder.getSupplyOrderId());
        params.put("refundNum",count);
        params.put("userReason",mallOrder.getRefundReasonWap());
        return sendRequest(params,AFTER_SALES);
    }

    /**
     * 确认订单
     * @return
     */
    public JSONObject confirmOrder(MallOrder mallOrder){
        JSONObject params = new JSONObject();
        params.put("orderSn",mallOrder.getSupplyOrderNo());
        params.put("paymentFee",mallOrder.getTotalPrice().multiply(BigDecimal.valueOf(100)).toBigInteger());
        params.put("payType",99);
        params.put("payId",mallOrder.getOrderNo());
        params.put("notifyUrl",sendNotifyUrl);
        return sendRequest(params,CONFIRM_ORDER);
    }


    /**
     * 通用请求接口
     * @param params
     * @param method
     * @return
     */
    private JSONObject sendRequest(JSONObject params, String method) {
        log.info("请求接口{}，参数{}",method,params);
        String data = Base64.encode(params.toJSONString());
        String sign = SecureUtil.md5(data + secretId).toUpperCase();
        JSONObject request = new JSONObject();
        request.put("appKey", appKey);
        request.put("data", data);
        request.put("sign", sign);
        JSONObject result = JSONObject.parseObject(HttpUtil.post(requestUrl + method, request.toJSONString()));
        log.info("supply请求地址{},参数{}，结果{}",requestUrl + method,request,result);
        if(StrUtil.equals(result.getString("code"),"10000")){
            return result;
        }
        throw new GlobalRunTimeException("智慧供应链请求失败:"+result.getString("message"));
    }

}
